from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from .neo4j_connection import graph
from .api_instance import api_instance


class ActionAskAboutRelation(Action):
    def name(self) -> Text:
        return "action_ask_about_relation"

    async def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        person_name = next(tracker.get_latest_entity_values("person"), None)

        person_list = graph.query_person(person_name)

        if not person_name:
            api_instance.ask(tracker.events, dispatcher)
            return []

        if not person_list:
            dispatcher.utter_message("不好意思，我不清楚你问的" + (person_name if person_name else "") + "是谁。", attachment="finish")
            return []

        records = graph.query_person_relation(person_name)

        if not records:
            dispatcher.utter_message("我不太清楚" + person_name + "的人际关系。", attachment="finish")
            return []

        relations = {}

        for record in records:
            relation_type = record["type"]

            if relation_type not in relations:
                relations[relation_type] = set()

            relations[relation_type].add(record["name"])

        message = person_name + "的人际关系有：\n"

        for key, value in relations.items():
            message += key + "：" + "，".join(value) + "\n"

        api_instance.optimize_response(tracker.events, message, dispatcher)
        return []
